package pers.ht.mbpo.service;

import net.sf.json.JSONArray;
import pers.ht.mbpo.bean.User;
import pers.ht.mbpo.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    private UserDao userDao = new UserDao();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");
        if ("insert".equals(action)){
            userDao.insert(new User(request.getParameter("username"),request.getParameter("password"),request.getParameter("nickname"),request.getParameter("college"),request.getParameter("major")));
            response.sendRedirect("UserServlet?action=query");
        }
        if ("update".equals(action)){
            userDao.edit(new User(request.getParameter("username"),request.getParameter("password"),request.getParameter("nickname"),request.getParameter("college"),request.getParameter("major")));
            response.sendRedirect("UserServlet?action=query");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if("query".equals(action)){
            List<User> users = userDao.query();
            String userJson = JSONArray.fromObject(users).toString();
            request.setAttribute("userJson",userJson);
            request.getRequestDispatcher("admin/user.jsp").forward(request, response);
        }
        if ("delete".equals(action)){
            String username = request.getParameter("username");
            userDao.delete(username);
            response.sendRedirect("UserServlet?action=query");
        }
        if ("find".equals(action)){
            String userId = request.getParameter("username");
            User user = userDao.queryOne(userId);
            request.setAttribute("user",user);
            request.setAttribute("flag",true);
            request.getRequestDispatcher("admin/AEUser.jsp").forward(request, response);
        }
        if ("add".equals(action)) {
            request.getRequestDispatcher("admin/AEUser.jsp").forward(request, response);
        }
    }
}
